import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/forgetPassword';
import Resend from '../components/forgetPassword/Resend';
import {
	i18n
} from '../public/i18n';
import {
	WeaLocaleProvider
} from 'ecCom';
import {
	RSAEcrypt
} from "../util/RSAUtil";
import {
	checkWeakPass
} from "../util/PASSUtil.js";

const getLabel = WeaLocaleProvider.getLabel;
const getLocaleLabelByLang = WeaLocaleProvider.getLocaleLabelByLang;

export class HrmForgetPassword extends HrmBaseStore {
	/********************* unobservable list *********************/
	openRSA = "0";
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
		]
		let menus = [];
		switch(this.step){
			case 1:
				btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ix7yv2@${this.step}`} type='primary' op='nextStep' onClick={this.forgotPasswordToNext}>{i18n.button.nextStep()}</Button>];
				break;
			case 2:
				btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nqdz2j@${this.step}`} type='primary' op='nextStep' onClick={this.checkFormInfo}>{i18n.button.verification()}</Button>];
				break;
			case 3:
				btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@e67amw@${this.step}`} type='primary' op='save' onClick={this.save}>{i18n.button.save()}</Button>];
				break;
		}
		btns.map((btn, index) => {
			const {
				props
			} = btn;
			menus.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick,
				disabled: props.disabled || false
			});
		})
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus()]
		}
	}

	itemRender = {
		type: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					<div style={{float: 'left', width: '60%'}}>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@msj8a8`} fieldConfig={{...field, ...textAreaProps}} 
							form={form} formParams={formParams} onChange={this.onWfChange} />
					</div>
				</div>
			)
		},
		loginid: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					<div style={{float: 'left', width: '60%'}}>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@69wxlx`} fieldConfig={{...field, ...textAreaProps}} 
							form={form} formParams={formParams} onChange={this.onWfChange} />
					</div>
				</div>
			)
		},
		validatecode: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					<div style={{float: 'left', width: '60%'}}>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@nb43e1`} fieldConfig={{...field, ...textAreaProps}} 
							form={form} formParams={formParams} onChange={this.onWfChange} />
					</div>
					<img style={{float: 'right'}} border="0" align='absmiddle' src={this.verificationCode} onClick={this.refreshVerificationCode} title={i18n.label.preview()} />
				</div>
			)
		},
		answer: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@i4ef8n`} fieldConfig={{...field, ...textAreaProps}} 
						form={form} formParams={formParams} onChange={this.onWfChange} />
					<a style={{lineHeight: '30px'}} onClick={this.reset}>{i18n.button.changeValidType()}</a>
				</div>
			)
		},
		phoneCode: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					<div style={{width: '40%', float: 'left'}}>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1rzjd4`} fieldConfig={{...field, ...textAreaProps}} 
							form={form} formParams={formParams} onChange={this.onWfChange} />
					</div>
					<Resend ecId={`${this && this.props && this.props.ecId || ''}_Resend@zn95gg`} store={this}/>
					{/* {
						this.showTimeout && <div style={{color: 'red', float: 'left', marginLeft: 20}}>{i18n.message.vCodeExpired()}</div>
					}
					<Button type={this.t > 0 ? 'default' : 'primary'} style={{float: 'left', marginLeft: 20}} onClick={this.resendVCode}>{this.sendBtnLabel}</Button> */}
				</div>
			)
		},
		emailCode: (field, textAreaProps, form, formParams) => {
			return this.itemRender.phoneCode(field, textAreaProps, form, formParams)
		}
	}

	id;
	targetInfo;
	langid;
	checkTimer;
	t = 60;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/

	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	@observable refreshForm = new Date().getTime();
	@observable step = 1;
	@observable verificationCode = '/weaver/weaver.file.MakeValidateCode?from=_forgort&isView=1&validatetype=0&validatenum=4&seriesnum_=' + new Date().getTime();
	@observable showTimeout = false;
	@observable sendBtnLabel = '';
	@observable spinning = false;
	/********************* observable list *********************/

	/********************* computed list *********************/
	/********************* computed list *********************/

	/********************* action list *********************/
	@action getDialogInfo = () => {};

	initData = (langid, getDialogInfo, callback) => {
		this.id = null;
		this.langid = langid;
		this.validatecode = null;
		this.type = null;
		this.targetInfo = '';
		this.step = 1;
		this.getDialogInfo = getDialogInfo;
		this.spinning = true;

		api.getForgotPasswordForm({languageId: this.langid}).then(data => {
			if(data.status === '1'){
				this.setFormData('findPasswordForm', data.conditions);
				this.spinning = false;
				if(this.formTarget.findPasswordForm.isFormInit){
					this.refreshForm = new Date().getTime();
					callback && callback();
				}
			}
		}, error => this.spinning = false)
	}

    @action
    refreshVerificationCode = () => {
        this.verificationCode = `/weaver/weaver.file.MakeValidateCode?from=_forgort&isView=1&validatetype=0&validatenum=4&&seriesnum_=${new Date().getTime()}`;
	}

	@action reset = () => {
		this.spinning = true;
		api.getForgotPasswordForm({languageId: this.langid}).then(data => {
			if(data.status === '1'){
				this.setFormData('findPasswordForm', data.conditions);
				this.spinning = false;
				this.id = null;
				this.validatecode = null;
				this.type = null;
				this.step = 1;
			}
		}, error => this.spinning = false)
	}
	
	@action getValidateCodeParam = () => {
		const params = this.formTarget.findPasswordForm.getFormParams();
		return {validatecode: params.validatecode, loginid: params.loginid, languageId: this.langid};
	}

	@action getInfoContent = (type) => {
		let content = (type === 'phoneCode' ? i18n.message.checkPhoneVCode() : i18n.message.checkMailVCode());
		content = content.replace('{params}', this.targetInfo);
		return content;
	}

	@action forgotPasswordToNext = () => {
		if(this.spinning)
			return;
		this.spinning = true;
		this.formTarget.findPasswordForm.validateForm().then(f => {
			if (f.isValid) {
				const formData = this.formTarget.findPasswordForm.getFormParams();
				api.forgotPasswordCheckMsg({...formData, languageId: this.langid}).then(data => {
					if(data.status === '1'){
						this.id = data.id;
						api.forgotPasswordToNext({id: this.id, ...formData, languageId: this.langid}).then(data => {
							if(data.status === '1'){
								this.targetInfo = data.id;
								this.t = ~~(data.forgotpasswordExpiration || 60);
								if(formData.type != '-1'){
									this.hint({
										content: <div><div>{this.getInfoContent(formData.type)}</div><div>{i18n.message.checkVCode()}</div></div>
									})
									this.getCheckForm().then(data => {
										if(data.status === '1'){
											this.setFormData('checkForm', data.conditions);
											this.step = 2;
											if(['phoneCode', 'emailCode'].indexOf(formData.type) > -1){
												this.sendBtnLabel = `${this.t.toString()}s`;
												this.showTimeout = false;
												this.checkTimer = setInterval(() => {
													this.sendBtnLabel = `${(--this.t).toString()}s`;
													if(this.t === 0){
														this.showTimeout = true;
														this.sendBtnLabel = i18n.button.resend();
														clearInterval(this.checkTimer);
													}
												}, 1000);
											}
											this.refreshVerificationCode();
										}else{
											this.hint({
												content: data.message
											});
											this.refreshVerificationCode();
										}
										this.spinning = false;
									})
								}else{
									this.getCheckForm().then(data => {
										if(data.status === '1'){
											this.setFormData('checkForm', data.conditions);
											this.step = 2;
											this.refreshVerificationCode();
										}else{
											this.hint({
												content: data.message
											})
											this.refreshVerificationCode();
										}
										this.spinning = false;
									})
								}
							}else{
								this.hint({
									content: data.message
								});
								this.spinning = false;
								this.refreshVerificationCode();
							}
						}, error => {
							this.spinning = false;
							this.refreshVerificationCode();
						})
					}else{
						this.hint({
							content: data.message
						});
						this.refreshVerificationCode();
						this.spinning = false;
					}
				}, error => {
					this.spinning = false;
					this.refreshVerificationCode();
				})
			} else {
				this.spinning = false;
				this.refreshVerificationCode();
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action getCheckForm = () => {
		switch(this.formTarget.findPasswordForm.getFormParams().type){
			case 'phoneCode':
				return api.confirmPhoneCodeForm(this.getValidateCodeParam());
			case '-1':
				return api.passwordQuestionForm(this.getValidateCodeParam());
			case 'emailCode':
				return api.confirmEmailCodeForm(this.getValidateCodeParam());
		}
	}

	@action checkFormInfo = () => {
		if(this.spinning)
			return;
		this.spinning = true;
		this.formTarget.checkForm.validateForm().then(f => {
			if (f.isValid) {
				const formData = this.formTarget.checkForm.getFormParams();
				const findPasswordFormData = this.formTarget.findPasswordForm.getFormParams();
				const params = {id: this.id, ...findPasswordFormData, ...formData, languageId: this.langid};
				this.doCheck(params).then(data => {
					if(data.status === '1'){
						api.resetPasswordForm(params).then(data => {
							if(data.status === '1'){
								this.setFormData('passwordForm', data.conditions);
								this.step = 3;
								this.refreshVerificationCode();
								this.openRSA = data.openRSA;
							}else{
								message.error(data.message);
								this.refreshVerificationCode();
							}
						}, error => {
							this.refreshVerificationCode();
						})
					}else{
						message.error(data.message);
						this.refreshVerificationCode();
					}
					this.spinning = false;
				}, error => {
					this.spinning = false;
					this.refreshVerificationCode();
				})
			} else {
				this.spinning = false;
				f.showErrors();
				this.showError = new Date().getTime();
				this.refreshVerificationCode();
			}
		});
	}

	@action doCheck = (params) => {
		switch(this.formTarget.findPasswordForm.getFormParams().type){
			case 'phoneCode':
				return api.confirmPhoneCodeToNext(params);
			case '-1':
				return api.passwordQuestionToNext(params);
			case 'emailCode':
				return api.confirmEmailCodeToNext(params);
		}
	}

	@action save = () => {
		if(this.spinning)
			return;
		this.spinning = true;
		this.formTarget.passwordForm.validateForm().then(f => {
			if (f.isValid) {
				const formData = this.formTarget.passwordForm.getFormParams();
				if(formData.newpswd != formData.cfmpswd){
					message.error(i18n.message.doubleCheckPwdFaild());
					this.spinning = false;
					this.refreshVerificationCode();
					return;
				}
				const fields = this.formTarget.passwordFormFields;
				const otherParams = fields[0].items[0].otherParams;
				if(!this.passwordVerification(formData.cfmpswd, otherParams.minpasslen, otherParams.passwordComplexity)){
					this.spinning = false;
					this.refreshVerificationCode();
					return;
				}
				let RSAParam = {
					'newpswd':this.formTarget.passwordForm.getFormParams().newpswd,
					'cfmpswd':this.formTarget.passwordForm.getFormParams().cfmpswd
				}
				RSAEcrypt(this.openRSA,RSAParam).then(RSAParam => {
					checkWeakPass(RSAParam.newpswd,()=>{
						api.saveResetPassword({id: this.id,
							...this.formTarget.findPasswordForm.getFormParams(),
							...this.formTarget.checkForm.getFormParams(),
							...this.formTarget.passwordForm.getFormParams(),
							...RSAParam,
							languageId: this.langid
						}).then(data => {
							let dia = this.getDialogInfo();
							if(dia){
								dia.callback && dia.callback(data);
								dia.close();
							}
						})
						this.spinning = false;
					},() => {
						this.spinning = false;
						this.refreshVerificationCode();
					});
				})
			} else {
				this.spinning = false;
				f.showErrors();
				this.showError = new Date().getTime();
				this.refreshVerificationCode();
			}
		});
	}

	@action passwordVerification = (val, minPassLen, passwordComplexity) => {
		let checkpass = true;
		if (val.length < minPassLen) {
			message.error(i18n.message.pwdLen() + minPassLen);
			return false;
		} else if (passwordComplexity == "1") {
			const complexity11 = /[a-z]+/;
			const complexity12 = /[A-Z]+/;
			const complexity13 = /\d+/;
			if (complexity11.test(val) && complexity12.test(val) && complexity13.test(val)) {
				checkpass = true;
			} else {
				message.error(i18n.message.pwdType());
				checkpass = false;
			}
		} else if (passwordComplexity == "2") {
			const complexity21 = /[a-zA-Z_]+/;
			const complexity22 = /\W+/;
			const complexity23 = /\d+/;
			if (complexity21.test(val) && complexity22.test(val) && complexity23.test(val)) {
				checkpass = true;
			} else {
				message.error(i18n.message.pwdType1());
				checkpass = false;
			}
		}else if(passwordComplexity=="3"){
			const complexity31 = /[a-zA-Z_]+/;
			const complexity32 = /\d+/;
			if(complexity31.test(val)&&complexity32.test(val)){
				checkpass = true;
			}else{
				message.error(i18n.message.pwdType2());
				checkpass = false;
			}
		  }
		return checkpass;
	}

	@action resendVCode = () => {
		if(this.spinning)
			return;
		if(this.showTimeout){
			this.spinning = true;
			const formData = this.formTarget.findPasswordForm.getFormParams();
			const checkFormParams = this.formTarget.checkForm.getFormParams();
			if(checkFormParams.validatecode === ''){
				this.formTarget.checkForm.showError('validatecode', getLabel('84270',"请输入验证码"));
				this.spinning = false;
				this.refreshVerificationCode();
				return;
			}
			api.forgotPasswordToNext({id: this.id, ...formData, languageId: this.langid, validatecode: checkFormParams.validatecode}).then(data => {
				if(data.status === '1'){
					this.formTarget.checkForm.resetConditionValue();
					this.refreshVerificationCode();
					this.showTimeout = false;
					this.targetInfo = data.id;
					this.hint({
						content: <div><div>{this.getInfoContent(formData.type)}</div><div>{i18n.message.checkVCode()}</div></div>
					})
					this.t = ~~(data.forgotpasswordExpiration || 60);
					this.sendBtnLabel = `${this.t.toString()}s`;
					this.checkTimer = setInterval(() => {
						this.sendBtnLabel = `${(--this.t).toString()}s`;
						if(this.t === 0){
							this.showTimeout = true;
							this.sendBtnLabel = i18n.button.resend();
							clearInterval(this.checkTimer);
						}
					}, 1000);
				}else{
					this.hint({
						content: data.message
					});
					this.refreshVerificationCode();
				}
				this.spinning = false;
			}, error => {
				this.spinning = false;
				this.refreshVerificationCode();
			})
		}
	}
	/********************* action list *********************/
}

export const hrmForgetPassword = new HrmForgetPassword();